export function getPermissions(key) {
	let map = {
		'camera': '摄像头',
		'userInfo': '用户信息'
	}
	return new Promise((resove, reject) => {
		uni.getSetting({
			success({
				authSetting
			}) {
				if (!authSetting[`scope.${key}`]) {
					uni.showModal({
						title: '温馨提示',
						content: `亲，授权${map[key]}后才能正常使用小程序功能`,
						showCancel: false,
						success() {
							uni.openSetting({
								success({
									authSetting
								}) {
									if (!authSetting[`scope.${key}`]) {
										uni.showToast({
											title: '授权失败',
											icon: 'error',
											duration: 2000
										});
										reject(false)
									} else {
										resove(true)
									}
								}
							})
						}
					})
				} else {
					resove(true)
				}
			}
		})
	})

}


export function getUserInfo() {
	return new Promise(async (resolve, reject) => {
		let permissions = await getPermissions('userInfo')
		if (!permissions) return reject()
		uni.getUserProfile({
			desc: '用于完善会员资料',
			success: res => {
				resolve(res)
			},
			fail: res => {
				//拒绝授权
				uni.showToast({
					title: '您拒绝了授权',
					icon: 'error',
					duration: 2000
				})
				reject(res)
				return
			}
		})
		// uni.showModal({
		// 	title: '使用当前小程序功能需要您的微信授权',
		// 	showCancel: false,
		// 	success() {
		// 		//如果用户点击了确定按钮

		// 	}
		// })
	})
}

export function extractImgSrc(htmlString) {
	const imgSrcRegex = /<img[^>]*src=["']([^"']*)["'][^>]*>/;
	const match = htmlString.match(imgSrcRegex);
	return match ? match[1] : null;
}

export function convertToBase64(filePath) {
	return new Promise(( resove, reject) => {
	  wx.getFileSystemManager().readFile({
		filePath: filePath,
		encoding: 'base64',
		success: function (res) {
		  const base64Data = res.data;
		  console.log('Base64 编码:', base64Data);
		  resove(base64Data)
		  // 你可以在这里将 Base64 编码的图片上传到服务器
		},
		fail: function (error) {
			reject(error)
			console.error('转换为 Base64 失败:', error);
		}
	  });
	})
};

export function downloadImage (url) {
	return new Promise(( resove, reject) => {
		resove(url)
		return
	  wx.downloadFile({
		url: url,
		success: async function (res) {
		  if (res.statusCode === 200) {
			const tempFilePath = res.tempFilePath;
			 const base64 = await convertToBase64(tempFilePath);
			 resove('data:image/jpeg;base64,' + base64)
		  }
		},
		fail: function (error) {
		  console.error('下载图片失败:', error);
		  reject(error)
		}
	  });
  })
};